package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author zhmwi
 * @Date 2021/7/5
 * @Dersciption
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;

    @Autowired
    private DictListener dictListener;

    @Cacheable(value = "dict",key = "'queryTreeChildById__'+#id")
    @Override
    public List<Dict> queryTreeChildById(@PathVariable Long id){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        //获取所有的字典集合 (如：查询所有的品牌手机:华为 小米 三星)
        List<Dict> dicts = dictMapper.selectList(queryWrapper);
        for (Dict dict : dicts) {
            //设置该字典是否有子类（如：华为是否有子型号）
            dict.setHasChildren(hasChildren(dict.getId()));
        }
        return dicts;
    }
    public boolean hasChildren(Long id){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        Integer count = dictMapper.selectCount(queryWrapper);
        return count > 0;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf8");
            //这里URLEncoder.encode可以防止中文乱码，当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition","attachment;filename="+fileName+".xlsx");
            //数据库中查询字典的全部字段
            List<Dict> dicts = baseMapper.selectList(null);
            ArrayList<DictEeVo> dictVos = new ArrayList<>();
            for (Dict dict : dicts) {
                //只需要导出部分字段Vo类
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict,dictEeVo);
                dictVos.add(dictEeVo);
            }
            EasyExcel.write(response.getOutputStream(),DictEeVo.class)
                    .sheet("数据字典")
                    .doWrite(dictVos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,dictListener)
                    .sheet()
                    .doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //根据字典类型编号和唯一value值获取字典值
    @Override
    public String getDictionaryNameByDictCodeAndValue(String dictCode, String value) {
        if (StringUtils.isEmpty(dictCode)){
            //通过唯一value查询
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
            return dict.getName();
        }else{
            //根据字典类型查询到父字典id
            //      例如根据dict_code(hostType)查询到医院等级
            Dict parentDict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictCode));
            //根据id作为pid 和 value的唯一性 查询子字典
            //      例如医院等级的id=10000 查询pid为10000的子类 +value的唯一性 获取唯一的字典值 三级甲等
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parentDict.getId())
                    .eq("value",value));
            return dict.getName();
        }
    }

    //根据dictCode获取下级节点 如根据省code查询出所有省份集合
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictCode获取父字典
        Dict parentDict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictCode));
        //把id作为pid查询子字典集合
        List<Dict> dicts = this.getByDictId(parentDict.getId());
        return dicts;
    }

    //根据dictId查询子类字典集合
    @Override
    public List<Dict> getByDictId(Long dictId) {
        List<Dict> dicts = baseMapper.selectList(new QueryWrapper<Dict>().eq("parent_id", dictId));
        return dicts;
    }
}
